package com.syni.mdd.yhd.common.all.service.impl;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.utils.common.utils.AppConfig;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.BaseJPADao;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsLocalLifeDao;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.localLife.BmsLocalLifeGoodsVo;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.yhd.common.all.vo.rp.localLife.LifeListRpVo;
import com.syni.mdd.yhd.common.all.vo.rp.localLife.LogisticsRpVo;
import com.syni.mdd.yhd.common.all.vo.rp.localLife.ProductDetailRpVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author: huangwenquan
* @date:  2020/2/24 14:50
* @description:本地生活
*/
@Service
@Log4j2
public class BmsLocalLifeServiceImpl extends BaseService<BmsLocalLife, Integer> implements BmsLocalLifeService {

    @Autowired
    BmsLocalLifeDao bmsLocalLifeDao;
    @Autowired
    BmsLocalLifeGoodsService bmsLocalLifeGoodsService;
    @Autowired
    BmsLocalLifeGoodsRelationService lifeGoodsRelationService;
    @Autowired
    BmsBusinessService bmsBusinessService;
    @Autowired
    BmsDxOrderStatusService bmsDxOrderStatusService;
    @Autowired
    ImgPrefixService imgPrefixService;
    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Override
    public BaseJPADao<BmsLocalLife, Integer> getBaseDao() {
        return bmsLocalLifeDao;
    }

    @Override
    public Map<String, Object> getLifeList(Integer pageNum,Integer pageSize) {
        pageNum  = pageNum < 0 ? 1 : pageNum;
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "updateTime");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",0);
        Page<BmsLocalLife> bmsLocalLifePage = bmsLocalLifeDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsLocalLife> bmsLocalLifeList = bmsLocalLifePage.getContent();
        for(BmsLocalLife b : bmsLocalLifeList){
            Integer businessId = b.getBusinessId();
            if(businessId!=null){
                Optional<BmsBusiness> oBmsBusiness = bmsBusinessService.getBaseDao().findById(businessId);
                if(oBmsBusiness.isPresent()){
                    b.setBusinessName(oBmsBusiness.get().getVendorName());
                }
            }
        }
        imgPrefixService.pushSpliceField(bmsLocalLifeList,"businessHeadImg","shareImg","qrCode","sources");
        return ResultMapHelper.success(bmsLocalLifeList,"OK");
    }

    @Override
    public Map<String, Object> getLifeList_V2(Integer pageNum,Integer pageSize) {
        pageNum  = pageNum < 0 ? 1 : pageNum;
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "updateTime");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("isDelete",0);
        List<BmsLocalLife> lifeList = bmsLocalLifeDao.findAll(new SpecificationUtils(conditionMap));
        Page<BmsLocalLife> bmsLocalLifePage = bmsLocalLifeDao.findAll(new SpecificationUtils(conditionMap),pageable);
        Set<Integer> lifeIds = new HashSet<>();
        List<LifeListRpVo> lifeListRpVos = new ArrayList<>();
        for(BmsLocalLife b : bmsLocalLifePage.getContent()){
            LifeListRpVo lifeListRpVo = new LifeListRpVo();
            List<String> imgUrls = JSON.parseArray(b.getSources(), String.class);
            if(imgUrls != null && imgUrls.size()>0){
                lifeListRpVo.setImgUrl(imgUrls.get(0));
            }
            BeanUtils.copyProperties(b,lifeListRpVo);
            lifeListRpVos.add(lifeListRpVo);
            lifeIds.add(b.getId());
        }
        if(lifeIds.size()>0){
            Map<Integer, Double> minMoneyMap = getMinMoneyByLifeIds(lifeIds);
            for(LifeListRpVo l : lifeListRpVos){
                if(minMoneyMap.containsKey(l.getId())){
                    l.setMinMoney(minMoneyMap.get(l.getId()));
                }
            }
        }
        Map<String,Object> params = new HashMap<>();
        params.put("count",lifeList.size());
        return ResultMapHelper.success(lifeListRpVos,params,ResultMsg.HAND_SUCCESS);
    }



    @Override
    public Map<String, Object> productDetail(ParamsMap paramsMap) {
        Map<String, Object> checkMap = checkLocalLife(paramsMap);
        if(checkMap != null && checkMap.get("status").equals("00")){
            BmsLocalLife bmsLocalLife = (BmsLocalLife)checkMap.get("data");
            Set<Integer> lifeId = new HashSet<>();
            lifeId.add(bmsLocalLife.getId());
            ProductDetailRpVo productDetailRpVo = new ProductDetailRpVo();
            Set<Integer> goodsId = new HashSet<>();
            List<BmsLocalLifeGoodsRelation> goodsRelation = lifeGoodsRelationService.findByLifeId(paramsMap.getInteger("lifeId"));
            for(BmsLocalLifeGoodsRelation b : goodsRelation){
                goodsId.add(b.getLocalLifeGoodsId());
            }
            Map<Integer, BmsLocalLifeGoods> bmsLocalLifeGoodMap = bmsLocalLifeGoodsService.getBmsLocalLifeGoodMap(goodsId);
            if(bmsLocalLifeGoodMap.size() >0 ){
                productDetailRpVo.setProductCount(bmsLocalLifeGoodMap.size());
            }else{
                productDetailRpVo.setProductCount(0);
            }
            Map<Integer, Double> minMoneyMap = getMinMoneyByLifeIds(lifeId);
            //浏览量+1
            bmsLocalLife.setPageviewNum(bmsLocalLife.getPageviewNum() + 1);
            bmsLocalLifeDao.saveAndFlush(bmsLocalLife);
            BeanUtils.copyProperties(bmsLocalLife,productDetailRpVo);
            if(minMoneyMap.containsKey(productDetailRpVo.getId())){
                productDetailRpVo.setMinMoney(minMoneyMap.get(productDetailRpVo.getId()));
            }
            Integer businessId = bmsLocalLife.getBusinessId();
            Optional<BmsBusiness> oBmsBusiness = bmsBusinessService.getBaseDao().findById(businessId);
            if(oBmsBusiness.isPresent()){
                productDetailRpVo.setBusinessName(oBmsBusiness.get().getVendorName());
            }
//            String prefixHtml = "<meta name=\"viewport\" content=\"width=100%,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0\">";
//            productDetailRpVo.setContent(prefixHtml.concat(productDetailRpVo.getContent()));
            return ResultMapHelper.success(productDetailRpVo,ResultMsg.HAND_SUCCESS);
        }else{
            return checkMap;
        }
    }

    @Override
    public Map<String, Object> getShareImg(ParamsMap paramsMap) {
        Map<String, Object> checkMap = checkLocalLife(paramsMap);
        if(checkMap != null && checkMap.get("status").equals("00")){
            BmsLocalLife bmsLocalLife = (BmsLocalLife)checkMap.get("data");
            return ResultMapHelper.success(bmsLocalLife.getShareImg(),"获取成功");
        }else{
            return checkMap;
        }
    }

    @Override
    public Map<String, Object> getLifeGoodsList(ParamsMap paramsMap) {
        Map<String, Object> userMap = new HashMap<>();
        Map<String, Object> checkMap = checkLocalLife(paramsMap);
        List<BmsLocalLifeGoods> goodsList = new ArrayList<>();
        if(checkMap != null && checkMap.get("status").equals("00")){
            BmsLocalLife bmsLocalLife = (BmsLocalLife)checkMap.get("data");
            //TODO 本地生活记录已在后台被下线
            if(bmsLocalLife.getIsDelete() == Constants.COMMON_FLAG_TRUE_INT){
                return ResultMapHelper.failure("该本地生活商品已下线");
            }
            Integer businessId = bmsLocalLife.getBusinessId();
            Optional<BmsBusiness> bmsBusinessOptional = bmsBusinessService.getBaseDao().findById(businessId);
            if(!bmsBusinessOptional.isPresent()){
                return ResultMapHelper.failure("商家不存在");
            }
            bmsLocalLife.setBusinessName(bmsBusinessOptional.get().getVendorName());
            List<BmsLocalLifeGoodsRelation> relations = lifeGoodsRelationService.findByLifeId(bmsLocalLife.getId());
            Set<Integer> goodIds = new HashSet<>();
            for(BmsLocalLifeGoodsRelation b : relations){
                goodIds.add(b.getLocalLifeGoodsId());
            }
            Map<Integer, BmsLocalLifeGoods> bmsLocalLifeGoodsMap = new HashMap<>();
            if(goodIds.size()>0){
                bmsLocalLifeGoodsMap = bmsLocalLifeGoodsService.getBmsLocalLifeGoodMap(goodIds);
            }
            for(BmsLocalLifeGoodsRelation b : relations){
                if(bmsLocalLifeGoodsMap.containsKey(b.getLocalLifeGoodsId())){
                    goodsList.add(bmsLocalLifeGoodsMap.get(b.getLocalLifeGoodsId()));
                }
            }

            //处理图片
            imgPrefixService.pushSpliceField(bmsLocalLife,"businessHeadImg","shareImg","sources");
            imgPrefixService.pushSpliceField(goodsList,"goodsImg");
            userMap.put("bmsLocalLife",bmsLocalLife);
            userMap.put("goodsList",goodsList);
            return ResultMapHelper.success(userMap,"获取成功");
        }else{
            return checkMap;
        }
    }

    @Override
    public Map<String, Object> cofirmGoods(ParamsMap paramsMap) {
        Integer orderId = paramsMap.getInteger("orderId");
        List<BmsDxOrderStatus> bmsDxOrderStatuses = bmsDxOrderStatusService.getBaseDao().findByOrderId(orderId);
        if(bmsDxOrderStatuses.size()>0){
            BmsDxOrderStatus bmsDxOrderStatus = bmsDxOrderStatuses.get(0);
            bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
            bmsDxOrderStatus.setFinishTime(new Date());
            bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);
        }else{
            return ResultMapHelper.failure("无订单获取状态");
        }
        /*Integer orderStatusId = paramsMap.getInteger("orderStatusId");
        BmsDxOrderStatus bmsDxOrderStatus = bmsDxOrderStatusService.getBaseDao().findById(orderStatusId).get();
        bmsDxOrderStatus.setStatus(Constants.PAY_COMPLETE);
        bmsDxOrderStatusService.getBaseDao().save(bmsDxOrderStatus);*/
        return ResultMapHelper.success("执行成功");
    }

    @Override
    public Map<String, Object> getLogisticsInfo (ParamsMap paramsMap) {
        //云市场分配的密钥Id
        String secretId = AppConfig.getProperty("cloud.logistics.secret.id");
        //云市场分配的密钥Key
        String secretKey = AppConfig.getProperty("cloud.logistics.secret.key");
        String source = "market";
        BufferedReader in = null;
        Optional<BmsDxOrder> oBmsDxOrder = bmsDxOrderService.getBaseDao().findById(paramsMap.getInteger("orderId"));
        if(!oBmsDxOrder.isPresent()){
            return ResultMapHelper.failure("该订单不存在");
        }
        BmsDxOrder bmsDxOrder = oBmsDxOrder.get();
        String companyCode = bmsDxOrder.getLogisticsCode() == null?"":bmsDxOrder.getLogisticsCode();
        String expressNo = bmsDxOrder.getLogisticsNum();
        if(expressNo.isEmpty() || expressNo == null){
            return ResultMapHelper.failure("暂无物流信息");
        }
        if(bmsDxOrder.getOrderType() != Constants.LOCAL_LIFE_ORDER_TYPE){
            return ResultMapHelper.failure("该订单不是本地生活订单");
        }
        LogisticsRpVo logisticsRpVo = new LogisticsRpVo();
        List<BmsLocalLifeGoodsVo> lifeGoodsVos = JSON.parseArray(bmsDxOrder.getShopList(), BmsLocalLifeGoodsVo.class);
        BmsLocalLifeGoodsVo bmsLocalLifeGoodsVo = lifeGoodsVos.get(0);
        Integer goodId = bmsLocalLifeGoodsVo.getGoodId();
        BmsLocalLifeGoods bmsLocalLifeGoods = bmsLocalLifeGoodsService.getBaseDao().findById(goodId).get();
        try{
            Calendar cd = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            String datetime = sdf.format(cd.getTime());
            // 签名
            String auth = LogisticsUtil.calcAuthorization(source, secretId, secretKey, datetime);
            // 请求方法
            String method = "GET";
            // 请求头
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("X-Source", source);
            headers.put("X-Date", datetime);
            headers.put("Authorization", auth);

            // 查询参数
            Map<String, String> queryParams = new HashMap<String, String>();
            queryParams.put("com", companyCode);
            queryParams.put("num", expressNo);
            // body参数
            Map<String, String> bodyParams = new HashMap<String, String>();

            // url参数拼接
            String url = "https://service-ohohpvok-1300683954.gz.apigw.tencentcs.com/release/express";
            if (!queryParams.isEmpty()) {
                url += "?" + LogisticsUtil.urlencode(queryParams);
            }

            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(60000);
            conn.setRequestMethod(method);

            // request headers
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // request body
            Map<String, Boolean> methods = new HashMap<>();
            methods.put("POST", true);
            methods.put("PUT", true);
            methods.put("PATCH", true);
            Boolean hasBody = methods.get(method);
            if (hasBody != null) {
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                conn.setDoOutput(true);
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                out.writeBytes(LogisticsUtil.urlencode(bodyParams));
                out.flush();
                out.close();
            }

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            String result = "";
            while ((line = in.readLine()) != null) {
                result += line;
            }
            logisticsRpVo = JSON.parseObject(result,LogisticsRpVo.class);
            logisticsRpVo.setGoodImg(bmsLocalLifeGoods.getGoodsImg());
            logisticsRpVo.setId(bmsDxOrder.getId());
            String state = logisticsRpVo.getState();
            switch (state){
                case "-1":logisticsRpVo.setState("单号或代码错误");break;
                case "0":logisticsRpVo.setState("暂无轨迹");break;
                case "1":logisticsRpVo.setState("快递收件");break;
                case "2":logisticsRpVo.setState("在途中");break;
                case "3":logisticsRpVo.setState("签收");break;
                case "4":logisticsRpVo.setState("问题件");break;
                case "5":logisticsRpVo.setState("疑难件");break;
                case "6":logisticsRpVo.setState("退件签收");break;
                default:logisticsRpVo.setState("");break;
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return ResultMapHelper.failure("捕获异常");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                return ResultMapHelper.failure("关闭异常");
            }
        }
        return ResultMapHelper.success(logisticsRpVo,ResultMsg.HAND_SUCCESS);
    }


    public Map<String,Object> checkLocalLife(ParamsMap paramsMap){
        Integer lifeId = paramsMap.getInteger("lifeId");
        if(lifeId==null){
            return ResultMapHelper.failure("请求参数数据类型出错");
        }
        Optional<BmsLocalLife> bmsLocalLifeOptional = bmsLocalLifeDao.findById(lifeId);
        if(!bmsLocalLifeOptional.isPresent()){
            return ResultMapHelper.failure("数据不存在");
        }else{
            //处理图片
            imgPrefixService.pushSpliceField(bmsLocalLifeOptional.get(),"shareImg");
            imgPrefixService.pushSpliceField(bmsLocalLifeOptional.get(),"sources");
            return ResultMapHelper.success(bmsLocalLifeOptional.get());
        }
    }


    @Override
    public Map<Integer, BmsLocalLife> getBmsLocalLifeMap(Set<Integer> lifeIds) {
        Map<Integer, BmsLocalLife> bmsLocalLifeMap = new HashMap<>();
        List<BmsLocalLife> bmsLocalLifeList = bmsLocalLifeDao.findByIdIn(lifeIds);
        if (bmsLocalLifeList != null && bmsLocalLifeList.size() > 0) {
            for (BmsLocalLife b : bmsLocalLifeList) {
                bmsLocalLifeMap.put(b.getId(), b);
            }
        }
        return bmsLocalLifeMap;
    }

    public Map<Integer,Double> getMinMoneyByLifeIds(Set<Integer> lifeIds){
        Map<Integer, Double> minMoneyMap = new HashMap<>();
        List<Map<Integer, Object>> minMoneyList = lifeGoodsRelationService.getMinMoney(lifeIds);
        for(Map<Integer, Object> m : minMoneyList){
            Integer id = null;Double min = null;
            for (Map.Entry<Integer, Object> entry : m.entrySet()) {
                if("local_life_id".equals(entry.getKey())){
                    id = Integer.parseInt(String.valueOf(entry.getValue()));
                }else{
                    min = Double.parseDouble(String.valueOf(entry.getValue()));
                }
            }
            minMoneyMap.put(id,min);
        }
        return minMoneyMap;
    }

}